package com.ferry.jraft.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author ferry
 * @create 2022/5/21 14:43
 * @description 节点的集合类
 */
public class PeerGroup implements Serializable {
    private static final long serialVersionUID = 6472620630944280596L;

    private List<Peer> peers;

    private volatile Peer leader;

    public PeerGroup(int capacity) {
        peers = new ArrayList<>(capacity);
    }

    public PeerGroup(List<Peer> peerList){
        peers=peerList;
    }

    public Peer getLeader() {
        return leader;
    }

    public void setLeader(Peer leader) {
        this.leader = leader;
    }

    public List<Peer> getPeers() {
        return peers;
    }

    /**
     * 获取除自身节点外的其他所有节点
     *
     * @return 除自身节点外的其他所有节点
     */
    public List<Peer> getOtherPeers(Peer self) {
        List<Peer> ret = new ArrayList<>(peers);
        ret.remove(self);
        return ret;
    }

    public Peer searchById(int id){
        for(Peer p:peers){
            if(p.getId()==id){
                return p;
            }
        }
        return null;
    }

    public void addPeer(Peer peer) {
        peers.add(peer);
    }

    public void removePeer(Peer peer) {
        peers.remove(peer);
    }

    @Override
    public String toString() {
        return "PeerGroup{" +
                "peers=" + peers +
                ", leader=" + leader +
                '}';
    }
}
